package com.boby.homecamera.webserver.controller

import com.boby.homecamera.config.AppConfig
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.util.JwtUtil
import com.boby.homecamera.webserver.model.UserInfo
import com.boby.lib_common.util.BLog
import com.boby.lib_common.util.MD5
import com.yanzhenjie.andserver.annotation.Addition
import com.yanzhenjie.andserver.annotation.GetMapping
import com.yanzhenjie.andserver.annotation.RequestMapping
import com.yanzhenjie.andserver.annotation.RequestMethod
import com.yanzhenjie.andserver.annotation.ResponseBody
import com.yanzhenjie.andserver.annotation.RestController
import com.yanzhenjie.andserver.error.HttpException
import com.yanzhenjie.andserver.http.HttpRequest
import com.yanzhenjie.andserver.util.MediaType

@RestController
@RequestMapping(path = ["/user"])
class UserController {
    private val TAG = "UserController"

    @GetMapping("/ping")
    fun ping(): String = "pong"

    @RequestMapping(path = ["/login"], method = [RequestMethod.POST])
    @ResponseBody
    fun login(request: HttpRequest): UserInfo {
        val username = request.getParameter("username")
        val password = request.getParameter("password")
        BLog.d(TAG,"login :" + username + ", "+ password)
         if (username == AppConfig.userName && password == MD5.digest(AppConfig.userPassword)) {
            val accessToken = JwtUtil.createAccessToken(username)
//            val refreshToken = JwtUtil.createRefreshToken(username)
           return UserInfo().apply {
               userId = "1"
               userName = username
               token = accessToken
               deviceId = AppConfig.did
           }
        }
        throw HttpException(Constant.ErrorCode.ERROR_CODE_LOGIN, "Account or password error .")
    }

    @Addition(stringType = ["login"], booleanType = [true])
    @GetMapping(path = ["/userInfo"], produces = [MediaType.APPLICATION_JSON_UTF8_VALUE] )
    fun  userInfo(): UserInfo {
        return UserInfo().apply {
            userId = "1"
            userName = AppConfig.userName
//            token = accessToken
            deviceId = AppConfig.did
        }
    }
}